package cn.unknownerror.ueteam.commands;

import cn.unknownerror.ueteam.PluginUETeam;
import cn.unknownerror.ueteam.data.ConfigurationManager;
import cn.unknownerror.ueteam.event.CreateTeamEvent;
import cn.unknownerror.ueteam.event.JoinTeamEvent;
import cn.unknownerror.ueteam.event.LeaveTeamEvent;
import cn.unknownerror.ueteam.event.TeamCallEvent;
import cn.unknownerror.ueteam.handle.CommandTeam;
import cn.unknownerror.ueteam.listener.PlayerChatListener;
import cn.unknownerror.ueteam.team.*;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

public class TeamCommand implements CommandExecutor {

    private ConfigurationManager config;

    public TeamCommand(ConfigurationManager config){
        this.config=config;
    }

    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if(args.length==0){
            help(sender,null);
            return true;
        }
        if(args[0].equals("call")){
            if(!sender.hasPermission("team.admin")){
                sender.sendMessage("§c你没有权限使用这个命令。");
                return true;
            }
            if(args.length<2) {
                sender.sendMessage("§c§l缺少参数，输入/team help查看帮助。");
                return true;
            }

            Player p = Bukkit.getPlayerExact(args[1]);
            if(p==null||!p.isOnline()){
                return true;
            }
            ITeam team = TeamAPI.findTeamFromPlayer(p.getUniqueId());
            if(team==null){
                return true;
            }
            if(!team.getCaptain().equals(p.getUniqueId())) return true;
            TeamCallEvent event=new TeamCallEvent(team);
            Bukkit.getPluginManager().callEvent(event);
            if(event.isCancelled()) return true;
            for(UUID uuid: team.getMembers()){
                Player member = Bukkit.getPlayerExact(Objects.requireNonNull(Bukkit.getServer().getOfflinePlayer(uuid).getName()));
                if(member==null||!member.isOnline()){
                    continue;
                }
                if(member.getUniqueId().equals(p.getUniqueId())) continue;
                if(member.getLevel()<650) continue;
                PlayerChatListener.followLocation.put(member.getUniqueId(),p);
                member.sendMessage("§7你的队长进入了Boss挑战,你可以在 §r5 §7秒内打开聊天框点击下方文本来跟随。");
                ComponentBuilder builder=new ComponentBuilder("   §7[§a§l§r跟随§7]").event(new ClickEvent(ClickEvent.Action.RUN_COMMAND,"follow"));
                member.spigot().sendMessage(builder.create());
                new BukkitRunnable(){
                    @Override
                    public void run() {
                        if(PlayerChatListener.followLocation.containsKey(member.getUniqueId())) {
                            PlayerChatListener.followLocation.remove(member.getUniqueId());
                            member.sendMessage("§c跟随请求已失效。");
                        }
                    }
                }.runTaskLater(PluginUETeam.getInstance(),100);
            }
            return true;
        }
        if(args[0].equals("reload")){
            PluginUETeam.getInstance().preload();
            sender.sendMessage("§a重载完成。");
            return true;
        }
        if(!(sender instanceof Player)){
            sender.sendMessage("你不能执行这个指令！");
            return true;
        }
        try{
            for (Method method:getClass().getDeclaredMethods()){
                method.setAccessible(true);
                SubCommand sub=method.getDeclaredAnnotation(SubCommand.class);
                if(sub==null){
                    continue;
                }
                if(sub.name().equalsIgnoreCase(args[0])){
                    String[] args1=new String[args.length-1];
                    for (int i = 1; i < args.length; i++) {
                        args1[i-1]=args[i];
                    }
                    method.invoke(this,sender,args1);
                    return true;

                }
            }
        }catch (Exception ignored){ }
        sender.sendMessage("§c错误的指令，请用/team help查看帮助");
        return true;
    }

    @SubCommand(name = "help",length = 0)
    public void help(CommandSender p,String[] args){
        p.sendMessage("§7§m--------§6§l[      Team      §6§l]§7§m--------");
        p.sendMessage("§a§l以下命令的参数[]为必填{}为可选");
        p.sendMessage("§a§l/team create [队伍名称] §e§l创建队伍");
        p.sendMessage("§a§l/team quit §e§l退出队伍");
        p.sendMessage("§a§l/team join [队伍名称]§e§l寻找并加入队伍");
        p.sendMessage("§a§l/team view §e§l查看当前所在队伍信息");
        p.sendMessage("§a§l/team call [队长名称]§e§l向该队长所在队伍所有在线成员发起召集");
        p.sendMessage("§a§l/team member §e§l查看所在队伍的队员列表");
        p.sendMessage("§a§l/team visible [true/false] §e§l队长可设置所在队伍能否加入。");
        p.sendMessage("§a§l/team list  §e§l查看现有的所有队伍列表。");
        p.sendMessage("§a§l/team reload §e§l重载插件");
    }

    @SubCommand(name="create",length = 1)
    public void create(Player p,String[] args){
        if(!p.hasPermission("team.use")){
            p.sendMessage("§c你没有权限使用这个命令。");
            return;
        }
        if(TeamAPI.findTeamFromPlayer(p.getUniqueId())!=null){
            p.sendMessage("§c§l你已经在一个队伍里了！");
            return;
        }
        try {
            CreateTeamEvent event =new CreateTeamEvent(
                    p,
                    TeamAPI.createTeam(TeamType.NormalTeam, args[0], new CommandTeam(config).getDefaultNum(), p.getUniqueId())
            );
            Bukkit.getPluginManager().callEvent(event);
            if(event.isCancelled()) TeamAPI.quitTeam(p.getUniqueId());
        }catch (Exception e){
            Bukkit.getServer().getLogger().warning(e.toString());
            for(StackTraceElement element : e.getStackTrace())
                Bukkit.getServer().getLogger().info(element.toString());
        }
        p.sendMessage("§a创建队伍成功! §7其他玩家可以使用 §r/team join "+ args[0]+" §7来加入你的队伍!");
    }

    @SubCommand(name="quit",length = 0)
    public void quit(Player p,String[] args){
        if(!p.hasPermission("team.use")){
            p.sendMessage("§c你没有权限使用这个命令。");
            return;
        }
        ITeam team =TeamAPI.findTeamFromPlayer(p.getUniqueId());
        if(team==null){
            p.sendMessage("§c§l没有加入队伍或者队伍已经解散。");
            return;
        }
        try {
            LeaveTeamEvent event = new LeaveTeamEvent(p,team);
            Bukkit.getPluginManager().callEvent(event);
            if(!event.isCancelled())
                TeamAPI.quitTeam(p.getUniqueId());
        }catch (Exception e){
            Bukkit.getServer().getLogger().warning(e.toString());
            for(StackTraceElement element : e.getStackTrace())
                Bukkit.getServer().getLogger().info(element.toString());
        }
        p.sendMessage("§a§l你现在是自由身了。");
    }

    @SubCommand(name="join",length = 1)
    public void join(Player p,String[] args){
        if(!p.hasPermission("team.use")){
            p.sendMessage("§c你没有权限使用这个命令。");
            return;
        }
        if(TeamAPI.findTeamFromPlayer(p.getUniqueId())!=null){
            p.sendMessage("§c§l你已经在一个队伍里了！");
            return;
        }
        List<ITeam> list = TeamAPI.findTeamFromName(args[0]);
        if(list==null||list.isEmpty()){
            p.sendMessage("§c§l找不到这支队伍。");
            return;
        }
        if(list.size()==1) {
            JoinTeamEvent event = new JoinTeamEvent(p,list.get(0));
            if(TeamAPI.joinTeam(p.getUniqueId(),list.get(0).getUUID())) {
                Bukkit.getPluginManager().callEvent(event);
                if(event.isCancelled()) TeamAPI.quitTeam(p.getUniqueId());
                p.sendMessage("§a§l您加入了队伍:" + list.get(0).getName());
            }
            else p.sendMessage("§c§l加入失败，可能是队伍人数已满,或者队伍禁止加入。");
        }else{
            p.sendMessage("§a§l你想加入的是以下哪一只队伍？请输入编号选择");
            int index=1;
            for(ITeam team : list){
                p.sendMessage(index+".§7§l队伍名: "+team.getName()+" §7§l队长: "+ Bukkit.getServer().getOfflinePlayer(team.getCaptain()).getName()+" §7§l人数: §f"+team.getMembers().size()+"§7/§f"+team.getMaxmember()+" §7§l状态: "+(team.getTeamState()?"§a可加入":"§c不可加入"));
                index++;
            }
            PlayerChatListener.teamSelection.put(p.getUniqueId(), (ArrayList<ITeam>) list);
        }
    }
    @SubCommand(name="view",length = 0)
    public void view(Player p,String[] args){
        if(!p.hasPermission("team.use")){
            p.sendMessage("§c你没有权限使用这个命令。");
            return;
        }
        if(TeamAPI.findTeamFromPlayer(p.getUniqueId())==null){
            p.sendMessage("§c§l没有加入队伍或者队伍已经解散。");
            return;
        }
        ITeam team=TeamAPI.findTeamFromPlayer(p.getUniqueId());
        p.sendMessage("§a§l队伍信息：");
        p.sendMessage(" §7§l名称: §f"+team.getName());
        p.sendMessage(" §7§l队长: §f"+Bukkit.getOfflinePlayer(team.getCaptain()).getName());
        p.sendMessage(" §7§l人数: §f"+team.getMembers().size()+"§7/§f"+team.getMaxmember());
        p.sendMessage(" §7§l状态: "+(team.getTeamState()?"§a可加入":"§c不可加入"));
    }

    @SubCommand(name="visible",length = 1)
    public void visible(Player p,String[] args){
        if(!p.hasPermission("team.use")){
            p.sendMessage("§c你没有权限使用这个命令。");
            return;
        }
        ITeam team = TeamAPI.findTeamFromPlayer(p.getUniqueId());
        if(team == null){
            p.sendMessage("§c§l没有加入队伍或队伍已经解散。");
            return;
        }
        if(!team.getCaptain().equals(p.getUniqueId())){
            p.sendMessage("§c§l你不是队伍的队长。");
            return;
        }
        if(args[0].equalsIgnoreCase("true")){
            team.setTeamState(true);
            p.sendMessage("§f§l设置队伍 §7"+team.getName()+" §f§l的状态为 §a可加入");
        }
        else if(args[0].equalsIgnoreCase("false")){
            team.setTeamState(false);
            p.sendMessage("§f§l设置队伍 §7"+team.getName()+" §f§l的状态为 §c不可加入");
        }else{
            p.sendMessage("§c参数格式错误，请输入/team help查看帮助。");
        }
    }

    @SubCommand(name="member",length = 0)
    public void member(Player p,String[] args){
        if(!p.hasPermission("team.use")){
            p.sendMessage("§c你没有权限使用这个命令。");
            return;
        }
        ITeam team = TeamAPI.findTeamFromPlayer(p.getUniqueId());
        if(team == null){
            p.sendMessage("§c§l没有加入队伍或队伍已经解散。");
            return;
        }
        p.sendMessage("§a§l队伍 §f"+team.getName()+" §a§l的队员列表：");
        int index = 2;
        OfflinePlayer captain =Bukkit.getOfflinePlayer(team.getCaptain());
        p.sendMessage(" §f"+1+".§e"+captain.getName()+"(队长)  §7§l在线状态: "+(captain.isOnline()?"§a在线":"§c不在线"));
        for(UUID member :team.getMembers()){
            OfflinePlayer m = Bukkit.getOfflinePlayer(member);
            if(m==null) continue;
            if(member.equals(team.getCaptain()))continue;
            p.sendMessage(" §f"+index+".§f"+m.getName()+"  §7§l在线状态: "+(m.isOnline()?"§a在线":"§c不在线"));
            index++;
        }
    }
    @SubCommand(name="list",length = 0)
    public void list(Player p,String[] args){
        if(!p.hasPermission("team.use")){
            p.sendMessage("§c你没有权限使用这个命令。");
            return;
        }
        p.sendMessage("§a§l队伍列表");
        if(TeamAPI.getTeamList().isEmpty()){
            p.sendMessage(" 暂无");
            return;
        }
        int index=1;
        for(ITeam team : TeamAPI.getTeamList()){
            p.sendMessage(" "+index+".§7§l队伍名: "+team.getName()+" §7§l队长: "+ Bukkit.getServer().getOfflinePlayer(team.getCaptain()).getName()+" §7§l人数: §f"+team.getMembers().size()+"§7/§f"+team.getMaxmember()+" §7§l状态: "+(team.getTeamState()?"§a可加入":"§c不可加入"));
            index++;
        }
    }
}
